import efinance as ef
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import re

plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

data_kua = pd.read_excel(r'c:\Users\Lenovo\Desktop\排名代码表.xlsx')
code_names = data_kua['问题1']
code_data = []
print(code_names)
for i in code_names:
    if i not in code_data:
        code_data.append(str(i))
print(code_data)

db_all_ = []

neam_ids = ef.futures.get_futures_base_info()
hua = 0.01
def get_name_index(name):
    return neam_ids['行情ID'][neam_ids[neam_ids['期货名称'] == f'{name}'].index.tolist()[0]]

def split_to_data(data,name,wheel):
    data_wheel = []
    for i in range(5,len(data)):
        data_wheel.append(np.average(data[name][i-wheel:i-1]))
    return data_wheel
def find_h_l(data,wheel):
    data_h = []
    data_l = []
    close_h = []
    close_l = []
    for i in range(5, len(data)):
        data_h.append(np.max(data['最高'][i - wheel:i - 1]))
        data_l.append(np.min(data['最低'][i - wheel:i - 1]))
        close_h.append(np.max(data['收盘'][i - wheel:i - 1]))
        close_l.append(np.min(data['收盘'][i - wheel:i - 1]))
    return data_h,data_l,close_h,close_l

def one_to(data_to_one):
    one_to_data = []
    pif = np.max(data_to_one) - np.min(data_to_one)
    for i in data_to_one:
        one_to_data.append((i - np.min(data_to_one))/pif)
    return one_to_data

def get_have(name:str)->str:
    name = re.findall("\d+",name)[0]
    return name

def main(index):
    """
    k1 = 0.5
    k2 = 0.1
    """
    k1 = 1
    k2 = 1
    wheel = 5
    m_time = 30
    id_futures = get_have(code_data[index])
    len_data = 0
    line_values = 0
    data_do = [[-3]]
    data_base = ef.stock.get_quote_history(id_futures, klt=5,beg='20231010',end='20231024')
    # print(data_base)
    if len(data_base) == 0:
        return
    try:
        data_base.to_excel(f"{str(data_base['日期'][0])[:-6]}.xlsx")
    except:
        pass
    data_day = np.array(data_base['日期'])
    data_base_open = np.array(data_base['开盘'])
    data_base_close = np.array(data_base['收盘'])
    data_base_zdf = np.array(data_base['涨跌幅'])
    benefit = []
    for i in range(len(data_base_close)-1):
        benefit.append(data_base_close[i+1]/data_base_close[i])
    beta = np.cov(benefit)/np.var(benefit)
    yuzhi = (data_base_zdf.max()-data_base_zdf.min())/2
    # print(data_base_zdf)
    # print(data_base.columns)
    # print(data_base)
    data_h, data_l, close_h, close_l = find_h_l(data_base,wheel)
    public_dates = ef.fund.get_public_dates(id_futures)
    kk = ef.fund.get_invest_position(id_futures, dates=public_dates[0])
    try:
        bodonglv = ((np.sum(kk['持仓占比']*kk['较上期变化'],axis=0))/10)
    except:
        bodonglv = None
    guo = 0.02
    for i in range(5,len(data_h)+5):
        range_k = max(data_h[i-5]-close_l[i-5],close_h[i-5]-data_l[i-5])
        buy_line = data_base_open[i] + k1*range_k
        sell_line = data_base_open[i] - k2*range_k
        if data_do[-1][0]:
            pass
        if data_base_close[i] > buy_line:
            if data_do[-1][0] != '买涨':
                # print('买涨',data_base_close[i])
                data_do.append(['买涨',data_base_close[i],i])
            else:
                pass
        if data_base_close[i] < sell_line:
            if data_do[-1][0] == '买涨':
                # print('卖出',data_base_close[i])
                data_do.append(['卖出', data_base_close[i],i])
            else:
                pass
        try:
            if data_do[-1][0] == '买涨' and data_base_zdf[i] > 0:
                # if data_base_zdf[i] > 0.6:
                #     data_do.append(['卖出', data_base_close[i], i])
                pass
            elif data_do[-1][0] == '买涨' and data_base_zdf[i] < 0:
                if data_base_zdf[i] < -yuzhi:
                    data_do.append(['卖出', data_base_close[i], i])
            elif data_do[-1][0] != '买涨' and data_base_zdf[i] < 0:
                # if data_base_zdf[i] < -0.6:
                #     data_do.append(['买涨', data_base_close[i], i])
                pass
            elif data_do[-1][0] != '买涨' and data_base_zdf[i] > 0:
                if data_base_zdf[i] > yuzhi:
                    data_do.append(['买涨', data_base_close[i], i])
        except:
            pass
    data_do_frame = pd.DataFrame(data_do[1:],columns=['方式','收盘价','时间'])
    data_do_frame.to_excel(rf'C:\Users\Lenovo\Desktop\A金融大湾区\回测数据\第一题\{id_futures}.xlsx')
    # plt.subplot(2,1,1)
    plt.plot(range(len(data_base_close)),data_base_close)
    win_number = 0
    a = []
    b = []
    for x,y,tp in zip(data_do_frame['时间'],data_do_frame['收盘价'],data_do_frame['方式']):
        color = str
        if tp != '买涨':
            color = 'g'
            a = plt.scatter(x, y, c=color)
        else:
            color = 'r'
            b = plt.scatter(x, y, c=color)

    plt.legend((a, b), ('卖出', '买入'), loc='best')
    # plt.subplot(2, 1, 2)
    # plt.plot(range(len(data_base['涨跌幅'])),one_to(data_base['涨跌幅']))
    plt.title(f'{id_futures}')
    plt.savefig(rf'C:\Users\Lenovo\Desktop\A金融大湾区\回测数据\第一题\{id_futures}.png')
    plt.show()
    win_arr = []
    lose_arr = []
    data_do = data_do[1:]
    for i in range(len(data_do)-1):
        if data_do[i][0] == '买涨':
            income = (data_do[i + 1][1]*(1-hua) - data_do[i][1])/data_do[i][1]
            if income >= 0:
                win_arr.append(income)
            else:
                lose_arr.append(income)
        else:
            income = (data_do[i][1] - data_do[i + 1][1]*(1-hua))/data_do[i][1]
            if income >= 0:
                win_arr.append(income)
            else:
                lose_arr.append(income)
    try:
        shouyilv = np.sum(win_arr)
        max_lose = np.min(lose_arr)
    except:
        shouyilv = None
        max_lose = None
    print('收益率',shouyilv)
    print('最大回撤',max_lose)
    print('Beta',beta)
    for i in data_do:
        i[2] = data_day[i[2]]
    # print(pd.DataFrame(data_do,columns=['行为','买入价','日期']))
    # win_arr.extend(lose_arr)
    try:
        xpl = (shouyilv - guo)/bodonglv
    except:
        xpl = None
    print('夏普率:',xpl)
    print(f'k1:{k1},k2:{k2}')
    print('--------------------------------------------------')
    db_all_.append([data_do,xpl,shouyilv,beta])
for index in range(len(code_data)):
    main(index)
print(db_all_)